package com.jeecms.wicool.action.groupBuy;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.jeecms.common.web.ResponseUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.jeecms.common.hibernate3.Updater;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.groupBuy.GroupBuy;
import com.jeecms.wicool.entity.orders.Orders;
import com.jeecms.wicool.entity.groupBuy.GroupBuySpecification;
import com.jeecms.wicool.entity.orders.Orders;
import com.jeecms.wicool.entity.product.Product;
import com.jeecms.wicool.entity.product.ProductCate;
import com.jeecms.wicool.entity.product.ProductSku;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.groupBuy.GroupBuyMng;
import com.jeecms.wicool.manager.orders.OrdersMng;
import com.jeecms.wicool.manager.product.ProductCateMng;
import com.jeecms.wicool.manager.product.ProductMng;
import com.jeecms.wicool.manager.product.ProductSkuMng;
import com.jeecms.wicool.manager.util.DictionaryMng;

/**
 * Created by cuiyanlei on 15/6/11.
 */
@Controller
@RequestMapping("/groupBuy")
public class GroupBuyAct {

    private static final Logger log = LoggerFactory.getLogger(GroupBuyAct.class);


    @RequestMapping("v_list.do")
    public String list(Integer productId, String content, Integer pageNo, HttpServletRequest request, ModelMap model) {
        Pagination pagination = manager.getPage(productId, content, cpn(pageNo), CookieUtils.getPageSize(request));
        List<ProductCate> productCates = productCateMng.getAll();
        model.addAttribute("listGroupBuy", pagination);
        model.addAttribute("productCates", productCates);
        model.addAttribute("pageNo", pageNo);
        return "group_buy/list_group_buy";
    }

    @RequestMapping("v_add.do")
    public String add(ModelMap model) {
        List<ProductCate> productCates = productCateMng.getAll();
        List<Product> products = Lists.newArrayList();
        List<ProductSku> specifications = Lists.newArrayList();
        model.addAttribute("productCates", productCates);
        model.addAttribute("products", products);
        model.addAttribute("specifications", specifications);
        return "group_buy/add_group_buy";
    }

    @RequestMapping("o_save.do")
    public String save(Integer productId, Integer specificationId, String startTime, String endTime, String content, String imgURL) {
        Product product = productMng.findById(productId);
        ProductSku productSku = productSkuMng.findById(specificationId);
        DateTime start = DateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        DateTime end = DateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
        DateTime createTime = DateTime.now();
        DateTime updateTime = DateTime.now();
        GroupBuy bean =
                new GroupBuy(null, product.getProductName(), null, productSku.getSkuName(), content, new Timestamp(start.getMillis()), new Timestamp(end.getMillis()), -1, imgURL, new Timestamp(createTime.getMillis()), new Timestamp(updateTime.getMillis()), product, productSku.getId(), null);
        bean.setSaleCount(0);
        manager.save(bean);

        return "redirect:v_list.do";
    }

    @RequestMapping("o_delete.do")
    public String delete(Integer[] ids) {
        for (Integer id : ids) {
            manager.deleteById(id);
        }
        return "redirect:v_list.do";
    }

    @RequestMapping("v_to_edit.do")
    public String toEdit(Integer id, ModelMap model) {
        model.addAttribute("groupBuyId", id);
        return "group_buy/to_edit_group_buy";
    }

    @RequestMapping("v_to_edit_group_buy.do")
    public String edit(Integer groupBuyId, ModelMap model) {
        GroupBuy bean = manager.findById(groupBuyId);
        Product product = bean.getProduct();
        List<ProductCate> tempCates = productCateMng.getAll();
        tempCates.remove(product.getProductCate());
        List<Product> tempProducts = productMng.getAll(product.getProductCate().getId());
        tempProducts.remove(product);
        List<ProductSku> tempProductSpecifications = productSkuMng.getListProductSku(product.getId());
        tempProductSpecifications.remove(bean.getProductSku());
        ImmutableSet<ProductCate> productCates = ImmutableSet.<ProductCate>builder().add(product.getProductCate()).addAll(tempCates).build();
        ImmutableSet<Product> products = ImmutableSet.<Product>builder().add(product).addAll(tempProducts).build();
        ImmutableSet<ProductSku> productSpecifications = ImmutableSet.<ProductSku>builder().add(productSkuMng.findById(bean.getProductSku())).addAll(tempProductSpecifications).build();
        model.addAttribute("productCates", productCates);
        model.addAttribute("products", products);
        model.addAttribute("specifications", productSpecifications);
        model.addAttribute("startTime", new DateTime(bean.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"));
        model.addAttribute("endTime", new DateTime(bean.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"));
        model.addAttribute("status", bean.getStatus());
        model.addAttribute("content", bean.getContent());
        model.addAttribute("groupBuyId", bean.getId());
        model.addAttribute("imgURL", bean.getImgURL());
        return "group_buy/edit_group_buy";

    }

    @RequestMapping("o_update.do")
    public String update(Integer groupBuyId, Integer productId, Integer specificationId, String imgURL, String startTime, String endTime, String content, ModelMap model) {
        GroupBuy bean = manager.findById(groupBuyId);
        Product product = productMng.findById(productId);
        ProductSku productSku = productSkuMng.findById(specificationId);
        bean.setProduct(product);
        bean.setProductName(product.getProductName());
        bean.setProductSku(specificationId);
        bean.setProductSpecificationName(productSku.getSkuName());
        bean.setStartTime(new Timestamp(DateTime.parse(startTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).getMillis()));
        bean.setEndTime(new Timestamp(DateTime.parse(endTime, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).getMillis()));
        bean.setContent(content);
        bean.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        bean.setImgURL(imgURL);
        manager.updateByUpdater(new Updater<GroupBuy>(bean));
        model.addAttribute("message", "global.success");
        return edit(groupBuyId, model);
    }

    @RequestMapping("o_update_status.do")
    public String updateStatus(Integer id, Integer status) {
        GroupBuy bean = manager.findById(id);
        bean.setStatus(status);
        Updater<GroupBuy> updater = new Updater<GroupBuy>(bean);
        manager.updateByUpdater(updater);
        return "redirect:v_list.do";
    }

    @RequestMapping("o_settlements.do")
    public void settlements(Integer id, ModelMap model, HttpServletResponse response){
    	 GroupBuy bean = manager.findById(id);
        JSONObject json = new JSONObject();
        int status = 1;
        json.put("message", "结算成功");
        if(bean == null) {
            status = -1;
            json.put("message", "没有找到相应的拼单记录！");
        }else{
    		 Set<GroupBuySpecification> specSet = bean.getSpecifications();
    		 if(specSet == null || specSet.isEmpty()) {
                 status = -2;
                 json.put("message", "没有找到相应的拼单规格记录！");
             }else{
    			manager.confirm(id);
             }
    	 }
        json.put("status", status);
        ResponseUtils.renderJson(response, json.toString());
    }
    
    @SuppressWarnings("unchecked")
	@RequestMapping("o_search_orders.do")
	public String searchOrders(Integer id,Integer pageNo,HttpServletRequest request,ModelMap model){
		Pagination pagination = ordersMng.getPage(1,id,cpn(pageNo),CookieUtils.getPageSize(request));
		List<Orders> listOrders =(List<Orders>) pagination.getList();
		List<Dictionary2> listDic=DicMng.getList("order_status");
		List<Dictionary2> listDic2=DicMng.getList("pay_type");
		List<Dictionary2> listDic3=DicMng.getList("activity_type");
		Map<String,String> map = new HashMap<String,String>();
		Map<String,String> map2 = new HashMap<String,String>();
		Map<String,String> map3 = new HashMap<String,String>();
		 for(Dictionary2 d : listDic){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 }
		 for(Dictionary2 d : listDic2){
			 map2.put(d.getDicCode().toString(), d.getDicName());
		 }
		 for (Dictionary2 d : listDic3) {
			 map3.put(d.getDicCode().toString(), d.getDicName());
		}
		 for(Orders o : listOrders){
			 if(map.containsKey(o.getStatus().toString())){
				 o.setStatusName(map.get(o.getStatus().toString()));
			 }
			 if(map2.containsKey(o.getPayway().toString())){
				 o.setPaywayName(map2.get(o.getPayway().toString()));
			 }
			 if(map3.containsKey(o.getType().toString())){
				 o.setTypeName(map3.get(o.getType().toString()));
			 }
		 }
		model.addAttribute("pagination", pagination);
		model.addAttribute("activityName", "拼单管理");
		model.addAttribute("id", id);
		return "orders/list_activity_orders";
	}
    
    @Autowired
    private GroupBuyMng manager;

    @Autowired
    private ProductMng productMng;

    @Autowired
    private ProductCateMng productCateMng;

    @Autowired
    private ProductSkuMng productSkuMng;

    @Autowired
	private OrdersMng ordersMng;
    
    @Autowired
   	private DictionaryMng DicMng;
   	
}
